//=============================================================================
// ItemValue.as
// 
// 
// AUTHOR:            Jay Liang
// 
//                  Copyright (c) 2011 Break Media
//                              All Rights Reserved.
//                          
//=============================================================================
package values.item
{
import com.adobe.serialization.json.JSON;

import flash.events.EventDispatcher;

import mx.utils.UIDUtil;

import values.dao_ns;

[Event(name="numChanged", type="values.events.ItemValueEvent")]
[Event(name="upgradeSuccess", type="values.events.ItemValueEvent")]
[Event(name="upgradeFail", type="values.events.ItemValueEvent")]

public class ItemValue extends EventDispatcher implements IItemValue
{    
	//==========================================================================
	//  Properties
	//==========================================================================
	protected var _uid:String = UIDUtil.createUID();

	dao_ns function set uid(value:String):void
	{
		_uid = value;
	}

	public function get uid():String
	{
		return _uid;
	}
	
	public function get key():String
	{
		return template.key;
	}
	
	protected var _template:ItemTemplateValue; 
	
	public function get template():ItemTemplateValue
	{
		return _template;
	}
	
	dao_ns function set template(value:ItemTemplateValue):void
	{
		_template = value;
	}
    
    public function get name():String
    {
        return template.name;
    }
    
    public function get desc():String
    {
        return template.desc;
    }
	
	protected var _params:Object;

	public function get params():Object
	{
		return _params;
	}	
	//==========================================================================
	//  Public methods
	//==========================================================================
	public function initialize(params:*):void
	{
		if (!params) params = {};
		
		_params = JSON.decode(JSON.encode(params));
	}
	
	public function dispose():void
	{
		
	}
	
	public function equals(value:IItemValue):Boolean
	{
		return key == value.key;
	}
	
	public function toObject():Object
	{
		return [ uid, key ];
	}
    
    override public function toString():String
    {
        return name;
    }
	//==========================================================================
	//  Class constants
	//==========================================================================
	public static function create(template:ItemTemplateValue, uid:String = null, params:* = null):IItemValue
	{
		var ref:Class = template.dynamicClassRef;
		var vo:IItemValue = new ref();
		vo.dao_ns::template = template;
		if (uid) vo.dao_ns::uid = uid;
		vo.initialize(params);
		return vo;
	}
	
	public static function createResource(key:String, num:Number, uid:String = null):ResourceItemValue
	{
		return ItemValue.create(ItemTemplateValueList.getByKey(key), uid, { num: num }) as ResourceItemValue;
	}
    
    /**
     * 参数格式: 
     * [ key, params ] 或者 [ uid, key, params ]
     * @param obj
     * @return 
     * 
     */    
    public static function createFromObject(obj:Array):IItemValue
    {
        //obj ->   [ uid, key, { params } ]  or [ key, { params } ]
        var uid:String = obj.length >= 3 ? obj[0] : UIDUtil.createUID();
        var key:String = obj.length >= 3 ? obj[1] : obj[0];
        var params:Object = obj.length >= 3 ? obj[2] : obj[1];
        var template:ItemTemplateValue = ItemTemplateValueList.getByKey(key);
        return ItemValue.create(template, uid, params);
    }
    
    /**
     * 参数格式: 
     * [ key, params ] 或者 [ uid, key, params ]
     * @param obj
     * @param num
     * @return 
     * 
     */    
    public static function createFromMutipleObject(obj:Array, num:Number):Vector.<IItemValue>
    {
        var items:Vector.<IItemValue> = new Vector.<IItemValue>();
        for (var i:int = 0; i < num; i++)
        {
            items.push(createFromObject(obj));
        }
        return items;
    }
    
    /**
     * 参数格式: 
     * [ [ key, params ], [ key, params ]... ] 
     * 或者
     * [ [ uid, key, params ], [ uid, key, params ]... ] 
     * @param objArray
     * @return 
     * 
     */    
    public static function createFromObjectArray(objArray:Array):Vector.<IItemValue>
    {
        var items:Vector.<IItemValue> = new Vector.<IItemValue>();
        for each (var obj:Array in objArray)
        {
            items.push(createFromObject(obj));
        }
        return items;
    }
	
	public static function convertToObject(value:Vector.<IItemValue>):Object
	{
		var obj:Array = [];
		for each (var vo:IItemValue in value)
		{
			obj.push(vo.toObject());
		}
		return obj;
	}
    
    public static function convertItemsToObjectArray(items:*):Array
    {
        var list:Array = [];
        for each (var item:IItemValue in items)
        {
            list.push(item.toObject());
        }
        return list;
    }
    
    public static function convertNumbericItemsToServerObject(value:Vector.<IItemValue>):Object
    {
        var obj:Object = {};
        for each (var vo:INumbericItemValue in value)
        {
            obj[vo.key] = vo.num;
        }
        return obj;
    }
	
	/**
	 *  
	 * @param value
	 * @param type    0 -> name x num;      1 -> num name
	 * @return 
	 * 
	 */	
	public static function convertToString(value:Vector.<IItemValue>, type:int = 0):String
	{
		var str:String = "";
		for each (var item:IItemValue in value)
		{
			var num:Number = 1;
			if (item is INumbericItemValue)
			{
				num = INumbericItemValue(item).num;
			}
			switch (type)
			{
				case 0:
					str += item.template.name + " x " + num;
					break;
				case 1:
					if (item is INumbericItemValue)
					{
						str += num + " ";
					}
					str += item.template.name;
					break;
			}
			str += ", ";
		}
		if (str != "")
		{
			str = str.substr(0, str.length - 2);
		}
		return str;
	}
}
}


